<template>
  <view class="post-images-container" v-if="images && images.length">
    <!-- 单张图片布局 -->
    <view class="post-image-wrapper" v-if="images.length === 1">
      <view v-if="images[0].needUnlock && !images[0].unlocked">
        <view class="post-single-image-container post-image-locked">
          <view class="lock-overlay"></view>
          <image :src="images[0].url" :alt="images[0].alt" class="post-image-single post-image-blur" mode="aspectFill"></image>
          <view class="post-lock-icon">
            <text class="tn-icon-lock"></text>
          </view>
        </view>
        <!-- 将按钮移到图片外面，使用与多图相同的样式 -->
        <button class="unlock-btn static-btn" @tap.stop="unlockImage(0)">
          <text class="tn-icon-unlock-fill" style="margin-right: 10rpx;"></text>
          {{ computedUnlockButtonText }}
        </button>
      </view>
      <view v-else class="post-single-image-container" @tap.stop="previewSingleImage(images[0].url)">
        <image 
          :src="images[0].url" 
          :class="[images[0].isPortrait ? 'post-image-portrait post-image-single' : 'post-image-landscape post-image-single']" 
          mode="aspectFill"
          @load="checkImageDimensions($event, images[0])"
          @error="handleImageError(images[0])"
          @tap.stop="previewSingleImage(images[0].url)"
        ></image>
        <view class="preview-indicator">
          <text class="tn-icon-eye"></text>
          <text class="indicator-text">预览</text>
        </view>
      </view>
    </view>
    
    <!-- 2-9张图片网格布局 -->
    <view class="post-image-wrapper" v-else-if="images.length > 1">
      <view :class="['post-images-grid', 'grid-' + images.length]">
        <!-- 需要解锁的图片 -->
        <view 
          v-for="(image, imgIndex) in lockedImages" 
          :key="image.id"
          class="post-image-item-container"
        >
          <image :src="image.url" class="post-image-item post-image-blur" mode="aspectFill"></image>
          <view class="post-lock-icon">
            <text class="tn-icon-lock"></text>
          </view>
        </view>
        <!-- 正常显示的图片 -->
        <view 
          v-for="(image, imgIndex) in unlockedImages" 
          :key="image.id"
          class="post-image-item-container"
          @tap.stop="previewImage(image.url, getPreviewUrls())"
        >
          <image 
            :src="image.url" 
            class="post-image-item" 
            mode="aspectFill"
            @error="handleImageError(image)"
          ></image>
        </view>
      </view>
      <!-- 多图解锁按钮 -->
      <button class="unlock-btn static-btn" v-if="hasLockedImages" @tap.stop="unlockAllImages">
        <text class="tn-icon-unlock-fill" style="margin-right: 10rpx;"></text>
        {{ computedUnlockButtonText }}
      </button>
    </view>
  </view>
</template>

<script>
// 引入广告工具类
import adHelper from '@/utils/adHelper.js';

export default {
  name: 'PostImages',
  props: {
    images: {
      type: Array,
      default: () => []
    },
    unlockButtonText: {
      type: String,
      default: '解锁高清图片'
    },
    postId: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      // 待解锁图片索引（单图模式）
      pendingUnlockIndex: -1,
      // 是否等待解锁所有图片（多图模式）
      isPendingUnlockAll: false
    };
  },
  computed: {
    computedUnlockButtonText() {
      return this.unlockButtonText || '解锁高清图片';
    },
    hasLockedImages() {
      return this.images.some(image => image.needUnlock && !image.unlocked);
    },
    // 新增计算属性，提前过滤出已锁定和已解锁的图片
    lockedImages() {
      return this.images.filter(img => img.needUnlock && !img.unlocked);
    },
    unlockedImages() {
      return this.images.filter(img => !img.needUnlock || img.unlocked);
    }
  },
  mounted() {
    // 无需额外初始化，adHelper 已在导入时自动初始化
  },
  methods: {
    /**
     * 解锁单张图片
     * @param {Number} imageIndex 图片索引
     */
    unlockImage(imageIndex) {
      console.log(`组件内部 - 尝试解锁图片, 帖子ID: ${this.postId}, 图片索引: ${imageIndex}`);
      
      if (!this.images[imageIndex]) return;
      
      // 保存待解锁的图片索引
      this.pendingUnlockIndex = imageIndex;
      
      if (adHelper.platform.isMpWeixin) {
        // 使用工具类显示广告确认弹窗
        adHelper.showAdConfirm(
          '解锁图片',
          '观看完整视频广告即可解锁高清图片',
          // 成功回调
          () => {
            this.completeUnlockImage(imageIndex);
          },
          // 失败回调
          (err) => {
            if (typeof err === 'string' && err === '用户未完整观看广告') {
              uni.showToast({
                title: '需要观看完整广告才能解锁',
                icon: 'none'
              });
              return;
            }
            
            // 显示失败处理
            uni.showModal({
              title: '提示',
              content: '广告加载失败，是否直接解锁？',
              success: res => {
                if (res.confirm) {
                  // 用户确认，仍然解锁
                  this.completeUnlockImage(imageIndex);
                }
                // 重置状态
                this.pendingUnlockIndex = -1;
              }
            });
          }
        );
      } else {
        // 非微信小程序环境，直接解锁
        this.completeUnlockImage(imageIndex);
      }
    },
    
    /**
     * 完成单张图片解锁
     * @param {Number} imageIndex 图片索引
     */
    completeUnlockImage(imageIndex) {
      // 通知父组件解锁图片
      this.$emit('unlock-image', imageIndex);
    },
    
    /**
     * 解锁所有图片
     */
    unlockAllImages() {
      console.log(`组件内部 - 尝试解锁所有图片, 帖子ID: ${this.postId}`);
      
      // 设置待解锁所有图片的标记
      this.isPendingUnlockAll = true;
      
      if (adHelper.platform.isMpWeixin) {
        // 使用工具类显示广告确认弹窗
        adHelper.showAdConfirm(
          '解锁所有图片',
          '观看完整视频广告即可解锁所有高清图片',
          // 成功回调
          () => {
            this.completeUnlockAllImages();
          },
          // 失败回调
          (err) => {
            if (typeof err === 'string' && err === '用户未完整观看广告') {
              uni.showToast({
                title: '需要观看完整广告才能解锁',
                icon: 'none'
              });
              return;
            }
            
            // 显示失败处理
            uni.showModal({
              title: '提示',
              content: '广告加载失败，是否直接解锁？',
              success: res => {
                if (res.confirm) {
                  // 用户确认，仍然解锁
                  this.completeUnlockAllImages();
                }
                // 重置状态
                this.isPendingUnlockAll = false;
              }
            });
          }
        );
      } else {
        // 非微信小程序环境，直接解锁
        this.completeUnlockAllImages();
      }
    },
    
    /**
     * 完成所有图片解锁
     */
    completeUnlockAllImages() {
      // 通知父组件解锁所有图片
      this.$emit('unlock-all-images');
    },
    
    /**
     * 检查图片尺寸
     * @param {Event} event 事件对象
     * @param {Object} image 图片对象
     */
    checkImageDimensions(event, image) {
      const img = event.target;
      const isPortrait = img.naturalHeight > img.naturalWidth * 1.2;
      this.$emit('image-dimensions-checked', { image, isPortrait });
    },
    
    /**
     * 处理图片加载错误
     * @param {Object} image 图片对象
     */
    handleImageError(image) {
      console.error(`图片加载失败: ${image.url}`);
      // 可以在这里设置默认图片或发出错误事件
      this.$emit('image-error', image);
    },
    
    /**
     * 获取可预览的图片URL列表
     * @returns {Array} URL列表
     */
    getPreviewUrls() {
      return this.images
        .filter(img => !img.needUnlock || img.unlocked)
        .map(img => img.url);
    },
    
    /**
     * 单张图片预览
     * @param {String} imageUrl 图片URL
     */
    previewSingleImage(imageUrl) {
      console.log(`组件内部 - 预览单张图片: ${imageUrl}, 帖子ID: ${this.postId}`);
      
      // 确保图片URL正确
      if (!imageUrl) {
        console.error('预览图片URL为空');
        return;
      }
      
      // 使用统一的预览方法，确保一致性
      this.previewImage(imageUrl, [imageUrl]);
    },
    
    /**
     * 多张图片预览
     * @param {String} current 当前图片URL
     * @param {Array} urls URL列表
     */
    previewImage(current, urls) {
      if (!urls || urls.length === 0) {
        console.error('预览图片URL列表为空');
        return;
      }
      
      console.log(`组件内部 - 预览图片: ${current}, URLs数量: ${urls.length}`);
      
      uni.previewImage({
        current: current,
        urls: urls,
        indicator: 'number',
        loop: true,
        success: () => {
          console.log('图片预览成功');
        },
        fail: (err) => {
          console.error('图片预览失败:', err);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.post-images-container {
  overflow: hidden;
  margin-bottom: 32rpx;
  border-radius: 24rpx;
}

.post-image-wrapper {
  width: 100%;
}

.post-single-image-container {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-bottom: 32rpx;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  border-radius: 24rpx;
  
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0);
    transition: background-color 0.2s ease;
    z-index: 1;
    border-radius: 24rpx;
  }
  
  &:active::after {
    background-color: rgba(0, 0, 0, 0.1);
  }
}

.post-image-single {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  border-radius: 24rpx;
  transition: transform 0.2s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.post-image-landscape {
  width: 100%;
  aspect-ratio: 16/9;
}

.post-image-portrait {
  width: 70%;  /* 竖向照片不占满宽度 */
  margin: 0 auto;
  aspect-ratio: 3/4;
}

.post-image-locked {
  position: relative;
  overflow: hidden;
  border-radius: 24rpx;
  background-color: rgba(0, 0, 0, 0.2);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
  width: 100%;
  /* 使用更合理的比例 */
  aspect-ratio: 16/9;
}

.post-image-blur {
  filter: blur(5px);
  opacity: 0.7;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 24rpx;
  transform: scale(1.05);
}

.post-lock-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient(45deg, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.8));
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  z-index: 2;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.4);
  
  .tn-icon-lock {
    font-size: 56rpx;
    color: #B3F73C;
    animation: wiggle 2s ease infinite;
    display: inline-block;
  }
}

@keyframes wiggle {
  0%, 100% { transform: rotate(0); }
  25% { transform: rotate(-10deg); }
  75% { transform: rotate(10deg); }
}

.unlock-btn {
  position: absolute;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  background: linear-gradient(45deg, #8eac21, #B3F73C);
  color: #050505;
  border: none;
  padding: 16rpx 36rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 500;
  z-index: 3;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.3);
  width: auto;
  max-width: 80%;
  transition: all 0.3s ease;
  animation: pulse 2s infinite;
  
  &:active {
    transform: translateX(-50%) scale(0.95);
    background: linear-gradient(45deg, #7c9b14, #a2e031);
    animation: none;
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(179, 247, 60, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(179, 247, 60, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(179, 247, 60, 0);
  }
}

.unlock-btn.static-btn {
  position: relative;
  transform: none;
  display: block;
  margin: 20rpx auto;
  bottom: auto;
  left: auto;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    background: linear-gradient(45deg, #7c9b14, #a2e031);
  }
}

.post-images-grid {
  display: grid;
  grid-gap: 8rpx;
  
  &.grid-2 {
    grid-template-columns: repeat(2, 1fr);
    aspect-ratio: 2/1;
  }
  
  &.grid-2 .post-image-item-container {
    aspect-ratio: 1/1;
  }
  
  &.grid-3 {
    grid-template-columns: repeat(3, 1fr);
    aspect-ratio: 3/1;
  }
  
  &.grid-3 .post-image-item-container {
    aspect-ratio: 1/1;
  }
  
  &.grid-4 {
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    aspect-ratio: 2/2;
  }
  
  &.grid-5 {
    display: grid;
    grid-template-columns: repeat(6, 1fr);
    grid-template-rows: repeat(2, 1fr);
    grid-template-areas:
        "img1 img1 img1 img2 img2 img2"
        "img3 img3 img4 img4 img5 img5";
    aspect-ratio: 16/9;
    grid-gap: 8rpx;
  }
  
  &.grid-5 .post-image-item-container:nth-child(1) {
    grid-area: img1;
  }
  
  &.grid-5 .post-image-item-container:nth-child(2) {
    grid-area: img2;
  }
  
  &.grid-5 .post-image-item-container:nth-child(3) {
    grid-area: img3;
  }
  
  &.grid-5 .post-image-item-container:nth-child(4) {
    grid-area: img4;
  }
  
  &.grid-5 .post-image-item-container:nth-child(5) {
    grid-area: img5;
  }
  
  &.grid-6 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 8rpx;
    aspect-ratio: 3/2;
  }
  
  &.grid-7 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: 2fr 1fr 1fr;
    grid-template-areas:
        "img1 img1 img2"
        "img3 img4 img5"
        "img6 img7 img7";
    gap: 8rpx;
    aspect-ratio: 3/3;
  }
  
  &.grid-7 .post-image-item-container:nth-child(1) {
    grid-area: img1;
  }
  
  &.grid-7 .post-image-item-container:nth-child(2) {
    grid-area: img2;
  }
  
  &.grid-7 .post-image-item-container:nth-child(3) {
    grid-area: img3;
  }
  
  &.grid-7 .post-image-item-container:nth-child(4) {
    grid-area: img4;
  }
  
  &.grid-7 .post-image-item-container:nth-child(5) {
    grid-area: img5;
  }
  
  &.grid-7 .post-image-item-container:nth-child(6) {
    grid-area: img6;
  }
  
  &.grid-7 .post-image-item-container:nth-child(7) {
    grid-area: img7;
  }
  
  &.grid-8 {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 8rpx;
    aspect-ratio: 4/2;
  }
  
  &.grid-9 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
    gap: 8rpx;
    aspect-ratio: 3/3;
  }
}

.post-image-item-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: 16rpx;
  
  .post-image-item {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 16rpx;
  }
}

.preview-indicator {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  background-color: rgba(5, 5, 5, 0.7);
  padding: 8rpx 16rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #B3F73C;
  z-index: 2;
  opacity: 0.7;
  
  .tn-icon-eye {
    font-size: 28rpx;
    margin-right: 6rpx;
  }
  
  .indicator-text {
    font-size: 24rpx;
  }
}

.post-single-image-container:active .preview-indicator {
  opacity: 1;
  background-color: rgba(108, 92, 231, 0.8);
}

.lock-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(0,0,0,0.3), rgba(0,0,0,0.7));
  z-index: 1;
  border-radius: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &::after {
    content: '';
    position: absolute;
    top: 30%;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style> 